<?php
namespace app\serversms\logic;

use \app\manage\logic\BaseLogic;

/**
 * @author:      李颖
 * @DateTime:    2017-06-26 15:40:01
 * @Description: 手机短信验证码类
 */
class Verify extends BaseLogic
{
	protected $name = 'verify';
    protected $config = 'db_config_sms';
    protected $verifyModel = 'app\serversms\model\Verify';
    protected $addField = ['mobile','token','type','verify','create_time'];
    
    //发送短信验证码
    public function sendVerify($data): array 
    {
        $data['type'] = $data['type'] . $data['code_id'];
        $data['verify'] = mt_rand(100000,999999);
        $sendData['send_info']['apikey'] = $data['sms_info']['apikey']; 
        $sendData['send_info']['mobile'] = $data['mobile']; 
        $sendData['send_info']['text'] = str_replace("#code#",$data['verify'],$data['sms_info']['text']);

        $smsName = config('smsName');
        if(!$smsName){
            return auto_failure(null, '未配置发送短信的方式');
        }

        try{
            $_where['mobile'] = $data['mobile'];
            $_where['token'] = $data['token'];
            $_where['type'] = $data['type'];
            $verifyInfo = $this->model($this->verifyModel)->where($_where)->find();
            if($verifyInfo){
                $updateVerify = $this->model($this->verifyModel)->save(['verify'=>$data['verify']], $_where); //更新验证码记录
            }else{
                $addVerify = $this->model($this->verifyModel)->allowField($this->addField)->save($data); //添加验证码记录
            }
        }catch (\Exception $e) {
            // 当唯一键重复等报错时
            return server_err(null, '数据库异常:' . $e->getMessage());
        }

        $sendData['smsName'] = $smsName;
        $res = logic('app\serversms\logic\Sms')->sendOne($sendData);
        if($res['status'] != SUCCESS_STATUS){
            return auto_failure(null, $res['msg']);
        }
        return auto_success(null, '成功发送验证码');
    }

    /*验证验证码*/
    public function checkVerify($data): array 
    {
        $data['type'] = $data['type'] . $data['code_id'];
        $_where['mobile'] = $data['mobile'];
        $_where['verify'] = $data['verify'];
        $_where['token'] = $data['token'];
        $_where['type'] = $data['type'];
        $info = $this->db()->where($_where)->find();
        $this->db()->where($_where)->delete();
        if($info){
            $time = $info['update_time'] ? $info['update_time'] : $info['create_time'];
            if(bcsub(NOW,$time) > config('sms_verification_time')){     //是否已经失效
                return verify_err($data, '验证码失效!!');
            }
            return auto_success(1, '短信验证码验证成功');
        }else{
            return auto_failure($data, '短信验证码验证失败');
        }
    }

    
}